#include "sockethelper.h"
#include<QMessageBox>

socketHelper* socketHelper::instance = nullptr;

socketHelper::socketHelper(QObject *parent) : QObject(parent)
{
    socket = new QTcpSocket(this);
    connect(socket,&QTcpSocket::readyRead,this,&socketHelper::onReadyRead);

    socket->connectToHost("127.0.0.1",8888);

}

socketHelper::~socketHelper()
{

}

void socketHelper::registHanler(MessagePackage &pack)
{
    bool ret = pack.result();
    if(ret)
    {
        emit registSuccess();
    }
    else
    {
        emit registFailed();
    }
}

void socketHelper::loginHanler(MessagePackage &pack)
{
    bool ret = pack.result();
    if(ret)
    {
        emit loginSuccess(pack.userName());
    }
    else
    {
        emit loginFailed();
    }
}

void socketHelper::onReadyRead()
{
    while(socket->bytesAvailable() > 0)
    {
        MessagePackage pack;
        MessagePackage::recvMessage(pack,socket);
        if(pack.type() == "regist")
        {
            registHanler(pack);
        }
        else if(pack.type() == "login")
        {
            loginHanler(pack);
        }
        else if(pack.type() == "update")
        {
            emit add_onl(pack.userName());
        }
        else if(pack.type() == "single")
        {
            emit this->recv_singleMessage(pack);
        }
        else if(pack.type() == "group_create_resp")
        {
            emit groupCreated(pack.result(), pack.groupId(), pack.groupName());
        }
        else if(pack.type() == "group_list")
        {
            QJsonDocument doc = QJsonDocument::fromJson(pack.getData());
            QJsonArray groups = doc.object()["groups"].toArray();
            emit groupListReceived(groups);
        }
        else if(pack.type() == "group_list_resp")
        {
            qDebug()<<"neng收到我所的列表 的";
            QJsonDocument doc = QJsonDocument::fromJson(pack.getData());
            QJsonArray groups = doc.object()["groups"].toArray();

            emit groupListReceived(groups);
        }
        else if(pack.type() == "group_message")
        {
            emit groupMessageReceived(pack);
        }
        else if(pack.type() == "test")
        {
            qDebug()<<"测试正常";
            qDebug()<<"neng收到我所的列表 的";
            QJsonDocument doc = QJsonDocument::fromJson(pack.getData());
            QJsonArray groups = doc.object()["groups"].toArray();
            emit groupListReceived(groups);
        }
        else if(pack.type() == "group_join_resp")
        {
            emit groupJoined(pack.result(), pack.groupId(), pack.groupName());
        }
        else if(pack.type() == "group_member_added")
        {
            emit groupMemberAdded(pack.groupId(), pack.userName());
        }
        else if(pack.type() == "group_invite")
        {
            QMessageBox::information(nullptr, "群组邀请", QString("您已被%1邀请加入群组: %2").arg(pack.userName()).arg(pack.groupName()));
        }
        else if (pack.type() == "group_list_update")
        {
            // 静默刷新群列表
            MessagePackage request;
            request.setType("group_list");
            request.setUserName(m_currentUser);
            MessagePackage::sendMessage(request, socket);
        }
        else if (pack.type() == "force_refresh")
        {
            qDebug()<<"能收到添加我让我跟新 的请求";
            // 立即请求最新群列表
            MessagePackage req;
            req.setType("group_list");
            req.setUserName(m_currentUser); // 使用之前方案存储的用户名
            MessagePackage::sendMessage(req, socket);
        }
        //文件 相关

        else if(pack.type() == "file_data")
        {
            QString filename = pack.groupName();
            QByteArray data = QByteArray::fromBase64(pack.getMessage().toLatin1());
            emit fileDataReceived(filename, data);
        }
        else if(pack.type() == "file_upload_ok")
        {
            emit fileUploadSuccess(); // 触发信号
        }
        // sockethelper.cpp（客户端）
        else if (pack.type() == "file_list")
        {
            // 1. 提取 data 字段中的文件数组
            QJsonArray files = pack.obj["data"].toArray();

            // 2. 调试输出
            qDebug() << "[Client] 收到的文件列表数据：" << files;

            // 3. 触发界面更新
            emit fileListReceived(files);
        }
        else if(pack.type() == "meeting_created")
        {
            emit meetingCreated(pack);
            qDebug() << "收到会议创建成功响应：" << pack.multicastIp() << ":" << pack.multicastPort();
        }
        else if(pack.type() == "meeting_joined")
        {
            emit meetingJoined(pack);
            qDebug() << "收到会议加入成功响应：" << pack.multicastIp() << ":" << pack.multicastPort();
        }
    }
}

socketHelper *socketHelper::getInstance()
{
    if(instance == nullptr)
    {
        instance = new socketHelper;
    }
    return instance;
}

void socketHelper::removeInstance()
{
    if(instance != nullptr)
    {
        delete instance;
        instance = nullptr;
    }
}

QTcpSocket *socketHelper::getSocket()
{
    return socket;
}

void socketHelper::setCurrentUser(const QString &username)
{
    m_currentUser = username;
}
void socketHelper::createMeeting()
{
    MessagePackage pack;
    pack.setType("create_meeting");
    pack.setUserName(m_currentUser);
    MessagePackage::sendMessage(pack, socket);
}

void socketHelper::joinMeeting(QString id)
{
    MessagePackage pack;
    pack.setType("join_meeting");
    pack.setUserName(m_currentUser);
    pack.setMeetingId(id);
    MessagePackage::sendMessage(pack, socket);
}
